<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

/**
 * 分类管理
 */
class Category extends Backend
{
    // 当前对象模型
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Subject.Category');
    }

    // 查看页面
    public function index()
    {
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加
    public function add()
    {
        if ($this->request->isPOST()) {
            $params = $this->request->post("row/a", [], 'trim');
            $result = $this->model->validate('common/Subject/Category')->save($params);
            if (!$result) {
                $this->error($this->model->getError());
            }

            $this->success();
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error('分类名称不存在');
        }
        if ($this->request->isPOST()) {
            $params = $this->request->post("row/a", [], 'trim');
            $params['id'] = $ids;
            $result = $this->model->validate('common/Subject/Category')->isUpdate()->save($params);
            if (!$result) {
                $this->error($this->model->getError());
            }

            $this->success();
        }
        $this->assign('row', $row);
        return $this->view->fetch();
    }
}
